package com.jckl.foodathon.restlet.clients;

import java.io.IOException;
import java.util.logging.Logger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.MediaType;
import org.restlet.resource.ClientResource;

public class GoogleGeocodingClient {
	
	private static final Logger log = Logger.getLogger(GoogleGeocodingClient.class.getName());
	final private String API_KEY = "AIzaSyDIeqdXSX2A4pDuRBzN-rEXcW38IFOh-W8";
	
	private String callGeoCoding(double latitude, double longitude){
		String returnString = "";
		
		StringBuffer URLbuffer = new StringBuffer("https://maps.googleapis.com/maps/api/geocode/json?");
		URLbuffer.append("latlng=");
		URLbuffer.append(latitude);
		URLbuffer.append(",");
		URLbuffer.append(longitude);
		URLbuffer.append("&key=");
		URLbuffer.append(API_KEY);
		
		String URL = URLbuffer.toString();
		
		try{
			ClientResource resource = new ClientResource(URL);
			resource.get(MediaType.APPLICATION_JSON);
			if(resource.getStatus().isSuccess()){
				returnString = resource.getResponseEntity().getText();
			}else{
				returnString = "An unexpected status was returned: "+resource.getStatus();
			}
		}catch (IOException ioEX){
			log.severe(returnString);
			ioEX.printStackTrace();
		}
		
		return returnString;
	}
	
	public String getRawLocation(double latitude, double longitude){
		return callGeoCoding(latitude, longitude);
	}
	
	public String getLocality(double latitude, double longitude){
		String jsonResponse = callGeoCoding(latitude, longitude);
		String locality = "";
		try {
			JSONObject geoCodeJson = new JSONObject(jsonResponse);
			JSONArray results = (JSONArray)geoCodeJson.get("results");
			JSONObject firstAddressComponent = results.getJSONObject(0);
			JSONArray addressComponenets = (JSONArray)firstAddressComponent.get("address_components");
			
			for(int i=0;i<addressComponenets.length();i++){
				JSONObject address = (JSONObject)addressComponenets.get(i);
				JSONArray types = (JSONArray)address.get("types");
				for(int y=0;y<types.length();y++){
					if(types.getString(y).equals("locality")){
						locality = address.getString("long_name");
						break;
					}
				}
			}
		} catch (JSONException jsonEx) {
			jsonEx.printStackTrace();
		}
		return locality;
	}
	

}
